const { createUser, getUserInfo, updateById } = require('../service/user.service')
const { JWT_SECRET } = require('../config/config.default')
const jwt = require('jsonwebtoken')

class UserController {
    async register(ctx, next) {
        const { user_name, password } = ctx.request.body
        const res = await createUser(user_name, password)
        ctx.body = {
            code: 0,
            message: '用户创建成功',
            result: {
                id: res.id,
                user_name: res.user_name
            }
        }
    }
    async login(ctx, next) {
        const { user_name } = ctx.request.body
        const { password, ...res } = await getUserInfo({ user_name })
        console.log(res)
        ctx.body = {
            code: 0,
            message: '用户登录成功',
            result: {
                token: jwt.sign(res, JWT_SECRET)
            }
        }
    }
    async changePassword(ctx, next) {
        const id = ctx.state.user.id
        const password = ctx.request.body.password
        const res = await updateById({ id, password })
        if (res) {
            ctx.body = {
                code: 0,
                message: '修改密码成功',
                result: ''
            }
        } else {
            ctx.body = {
                code: 0,
                message: '修改密码失败',
                result: ''
            }
        }
    }
}

module.exports = new UserController()
